'use strict';

const { Service } = require('egg');
const ModelName = 'City'
class RouterService extends Service {
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            where,
            offset: pageSize * (page - 1),
            limit: pageSize,
            order:[
                // id 降序
                ['sort','DESC'],
                ['create_time','DESC']
            ],
            include: [
                {
                    model: this.ctx.model[ModelName],
                    as: 'parent',
                    attributes: ['id', 'name'],
                },
                {
                    model: this.ctx.model[ModelName],
                    as: 'children',
                    attributes: ['id', 'name']
                }
            ]
        });
    }
    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
                ['create_time','DESC']
            ],
            include: [
                {
                    model: this.ctx.model[ModelName],
                    as: 'parent',
                    attributes: ['id', 'name'],
                },
                {
                    model: this.ctx.model[ModelName],
                    as: 'children',
                    attributes: ['id', 'name'],
                    // 需要无限递归
                    include: [
                        {
                            model: this.ctx.model[ModelName],
                            as: 'children',
                            attributes: ['id', 'name'],
                            include: [
                                {
                                    model: this.ctx.model[ModelName],
                                    as: 'children',
                                    attributes: ['id', 'name'],
                                    include: [
                                        {
                                            model: this.ctx.model[ModelName],
                                            as: 'children',
                                            attributes: ['id', 'name'],
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        });
    }
    async findOne(id) {
        return this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
        });
    }
    async create(data) {
        return this.ctx.model[ModelName].create(data);
    }
    async update(id, data) {
        return await this.ctx.model[ModelName].update(data, { where: { id } });
    }
    async deleteById(id) {
        return await this.ctx.model[ModelName].destroy({ where: { id } });
    }
}

module.exports = RouterService;
